/**
 * @Author: Kindear
 * @Date: 2021-09-08
 * @Desc: 用于查询空课表的云函数构建
 */

if (!Promise.allSettled) {
    const rejectHandler = reason => ({
        status: "rejected",
        reason
    })
    const resolveHandler = value => ({
        status: "fulfilled",
        value
    })
    Promise.allSettled = promises =>
        Promise.all(
            promises.map((promise) =>
                Promise.resolve(promise)
                .then(resolveHandler, rejectHandler)
            )
            // 每个 promise 需要用 Promise.resolve 包裹下
            // 以防传递非 promise
        );
}
async function execPromise(tasks) {
    return new Promise(function (resolve, reject) {
        Promise.all(tasks).then(res => {
            resolve(res)
            reject(res)
        })
    })
}
async function execPromiseSettled(tasks) {
    return new Promise(function (resolve, reject) {
        Promise.allSettled(tasks).then(res => {
            resolve(res)
            reject(res)
        })
    })
}
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const EMPTY = 'cloud-edu-empty';
const timeutil = require('./timeutil');
// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    let openid = event.openid || wxContext.OPENID;
    console.log('OPENID : '+openid)
    let action = event.action;
    switch (action) {
        case 'getEmpty': {
            let date = timeutil.TimeCodeYmd();
            /**先查询数据表 */
            let queryRes = await db.collection(EMPTY).where({
                date,
                idleTime:event.idleTime
            }).get();
            if(queryRes.data.length == 0){
                let res =  await cloud.callFunction({
                    name: 'edu-cloud-api',
                    data: {
                        openid:openid,
                        action: 'getKxJscx',
                        idleTime: event.idleTime,
                        resHandle: true
                    },
                })
                console.log(res)
                if(res.result.errCode!=-1){
                    db.collection(EMPTY).add({
                        data:{
                            date,
                            idleTime:event.idleTime,
                            emptyData:res.result
                        }
                    })
                }
                
                return res.result;
            }else{
                let res = queryRes.data[0].emptyData
                return res;
            }
            break
        }
    }
}